<template>
  <div class="employees-container">
    <div class="app-container">
      <page-tools>
        <template #left>
          <span>总记录数: {{ total }} 条</span>
        </template>
        <template #right>
          <el-button type="warning" size="small" @click="goExcel">excel导入</el-button>
          <el-button type="danger" size="small" @click="toExcel">excel导出</el-button>
          <el-button type="primary" size="small" @click="hAdd">新增员工</el-button>
        </template>
      </page-tools>

      <el-card style="margin-top: 10px;">
        <el-table border :data="list" :default-sort="{ prop: 'workNumber', order: 'descending' }">
          <el-table-column label="序号" type="index" />
          <el-table-column label="姓名" prop="username" />
          <el-table-column label="工号" prop="workNumber" />
          <el-table-column label="聘用形式">
            <template slot-scope="scope">
              类型：{{ formatHireType(scope.row.formOfEmployment) }}
            </template>
          </el-table-column>
          <el-table-column label="部门" prop="departmentName" />
          <el-table-column label="入职时间" prop="timeOfEntry" sortable />
          <!-- <el-table-column label="账户状态" /> -->
          <el-table-column label="操作" width="280">
            <template #default="{ row }">
              <el-button type="text" size="small" @click="$router.push(`/employees/detail?id=${row.id}`)">查看</el-button>
              <el-button type="text" size="small" @click="hEditRole(row.id)">分配角色</el-button>
              <el-button type="text" size="small" @click="hDel(row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row type="flex" justify="center" align="middle" style="height: 60px">
          <el-pagination
            :current-page="pageParams.page"
            :page-sizes="[1,5,10,15,20]"
            :page-size="pageParams.size"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </el-row>
      </el-card>
      <el-dialog
        title="新增员工"
        :visible.sync="showDialog"
        @close="hClose"
      >
        <addor-edit
          v-if="showDialog"
          ref="myEmp"
          @close="showDialog=false"
          @success="hSuccess"
        />
      </el-dialog>
      // 使用组件
      <el-dialog
        title="分配角色"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
        :visible.sync="showDialogRole"
      >
        <assign-role v-if="showDialogRole" ref="assignRole" :user-id="userId" @close="showDialogRole=false" />
      </el-dialog>
    </div>
  </div>
</template>
<script>
import AssignRole from './assignRole'
import addorEdit from './empDialog'
import { getEmployeeList, delEmployee } from '@/api/employees'
import employeeEnum from '@/constant/employees'
const hireType = employeeEnum.hireType.reduce((acc, item) => {
  acc[item.id] = item.value
  return acc
}, {})
export default {
  components: {
    addorEdit, AssignRole // 注册组件
  },
  data() {
    return {
      list: [],
      pageParams: {
        page: 1, // 页码值
        size: 5 // 每页显示条数
      },
      total: 0,
      showDialog: false,
      showDialogRole: false,
      userId: '' // 当前的员工编号
    }
  },
  created() {
    this.loadEmployeeList()
  },
  methods: {
    hEditRole(id) {
      console.log('当前要分配角色id是', id)
      this.showDialogRole = true
      this.userId = id
      this.$nextTick(() => {
        this.$refs.assignRole.loadRoles()
        // console.log('子组件中的props', this.$refs.assignRole.employeeId)
      })
    },
    // 格式化excel的数据格式
    formatToExcel(list) {
      //    中引文的映射对象
      const mapInfo = {
        'id': '编号',
        'password': '密码',
        'mobile': '手机号',
        'username': '姓名',
        'timeOfEntry': '入职日期',
        'formOfEmployment': '聘用形式',
        'correctionTime': '转正日期',
        'workNumber': '工号',
        'departmentName': '部门',
        'staffPhoto': '头像地址'
      }

      // tHeader = ['编号','密码','手机号','姓名','入职日期',.......]

      // 1 生成表头
      const one = list[0] // unfined || 有数据
      if (!one) return
      //  Object.keys(one)---> ['correctionTime','id','password','mobile']
      const tHeader = Object.keys(one).map(enkey => {
        return mapInfo[enkey]
      })
      console.log(tHeader, 'tHeader')
      // tHeader  ---> ['转正日期', '部门', '聘用形式', '编号', '手机号', '密码', '头像地址', '入职日期', '姓名', '工号']
      // 2 生成表的内容data
      const result = list.map(item => {
        return Object.values(item)
      })

      return { tHeader, result }
    },
    // 导出
    toExcel() {
      // 1.发送请求获取需要导出的数据
      // 页面渲染的时候已经发送请求将数据保存到this.list中
      // 2.将数据格式成Excel需要的格式
      const { tHeader, result } = this.formatToExcel(this.list)
      console.log(tHeader, 'tHeader')
      console.log(result, 'result')
      // 3.调用admin提供的函数,将数据写入到Excel
      import('@/vendor/Export2Excel').then(excel => {
        excel.export_json_to_excel({
          header: tHeader,
          data: result,
          filename: '',
          autoWidth: true,
          bookType: 'xlsx'
        })
      })
    },
    // 导入
    goExcel() {
      this.$router.push('/import')
    },
    // 关闭弹层重置表单
    hClose() {
      this.$refs.myEmp.resetForm()
    },
    hAdd() {
      this.showDialog = true
    },
    hSuccess() {
      this.showDialog = false
      // 添加成功，进入最后一页看数据
      this.total++
      // 最后一页
      this.pageParams.page = Math.ceil(this.total / this.pageParams.size)
      this.loadEmployeeList()
    },
    hDel(id) {
      this.$confirm('您确定要删除这个角色吗?').then(async() => {
        const res = await delEmployee(id)
        if (this.list.length === 1) {
          this.pageParams.page--
          if (this.pageParams.page <= 0) {
            this.pageParams.page = 1
          }
        }
        console.log(res, 'delEmployee')
        if (res.code === 10000) {
          // 1. 提示
          this.$message({ type: 'success', message: '删除成功!' })
          // 2. 更新数据
          this.loadEmployeeList()
        }
      }).catch(() => {
        this.$message({ type: 'info', message: '已取消删除' })
      })
    },
    formatHireType(value) {
      console.log(value, 'value')
      // const obj = employeeEnum.hireType.find(item => item.id === value)
      // return obj ? obj.value : '未知'
      return hireType[value] || '未知'
    },
    // 当每页显示的条数进行切换时触发 ---> val :每页显示的条数
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
      this.pageParams.page = 1
      this.pageParams.size = val
      this.loadEmployeeList()
    },
    // 当期的页码值进行切换时触发 ---> val :当前的页码值
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`)
      this.pageParams.page = val
      this.loadEmployeeList()
    },
    async loadEmployeeList() {
      try {
        const res = await getEmployeeList(this.pageParams.page, this.pageParams.size)
        console.log(res, 'getEmployeeList')
        this.list = res.data.rows
        this.total = res.data.total
      } catch (error) {
        console.log(error)
      }
    }
  }
}
</script>
